<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS绘图与动画系列 Core Graphics与Quartz 2D（一）"><meta name="keywords" content="iOS,动画,绘图"><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS绘图与动画系列 Core Graphics与Quartz 2D（一） | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Quartz-frameworks-%E5%8F%8A%E5%85%B6-APIs"><span class="toc-number">1.</span> <span class="toc-text">Quartz frameworks 及其 APIs</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%9B%BE%E5%83%8F%E7%9A%84%E9%87%8D%E7%BB%98%EF%BC%88%E5%88%B7%E5%B8%A7%EF%BC%89"><span class="toc-number">1.0.1.</span> <span class="toc-text">图像的重绘（刷帧）</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#drawRect%E6%96%B9%E6%B3%95%E4%BD%BF%E7%94%A8%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-number">1.1.</span> <span class="toc-text">drawRect方法使用注意点</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%BB%E5%9B%BE%E4%BA%8B%E4%BE%8B"><span class="toc-number">2.</span> <span class="toc-text">画图事例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%8E%AF%E5%BD%A2"><span class="toc-number">3.</span> <span class="toc-text">环形</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%98%E5%88%B6%E6%96%87%E6%9C%AC%E5%86%85%E5%AE%B9"><span class="toc-number">3.1.</span> <span class="toc-text">绘制文本内容</span></a></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS绘图与动画系列 Core Graphics与Quartz 2D（一）</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2016-04-06</time></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>iOS绘图Core Graphics与Quartz 2D</p>
<p><strong>Quartz Core, Core Graphics and Quartz 2D之间的区别</strong><br><a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/1877987/whats-the-difference-between-quartz-core-core-graphics-and-quartz-2d">StackFlow</a></p>
<h3 id="Quartz-frameworks-及其-APIs"><a href="#Quartz-frameworks-及其-APIs" class="headerlink" title="Quartz frameworks 及其 APIs"></a>Quartz frameworks 及其 APIs</h3><p><code>CoreGraphics.framework</code></p>
<p><code>Core Graphics</code>是一套C语言 API框架， 支持向量图形，线、形状、图案、路径、剃度、位图图像和pdf 内容的绘制。我们平时常见的各种UIKit框架提供的UI控件，实际上都是由Core Graphics进行绘制的。</p>
<ul>
<li><p><a target="_blank" rel="noopener" href="https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html#//apple_ref/doc/uid/TP30001066">Quartz 2D</a> 指一组二维绘图与渲染的 API。它是Core Graphics框架的一部分， CoreGraphics 有时候也被成为 Quartz 2D。因此我们一般都是用CGxxxx命名的函数进行绘图。</p>
<p><strong>Quartz 2D支持功能</strong>：Quartz是资源和设备无关的,提供基本路径绘制，剃度填充图案，图像，透明绘制和透明层、遮蔽和阴影、颜色管理，坐标转换，字体、offscreen呈现、pdf文档创建、显示和分析等功能。</p>
<p>具体可实现功能如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">绘制图形:线条、三角形、矩形、圆、弧等</span><br><span class="line">绘制文字</span><br><span class="line">绘制\生成图片(图像)</span><br><span class="line">读取\生成PDF</span><br><span class="line">截图\裁剪图片</span><br><span class="line">自定义UI控件 (iOS中大部分控件的内容都是通过Quartz2D画出来的)</span><br></pre></td></tr></table></figure>

<p>官方Demo:<a target="_blank" rel="noopener" href="http://developer.apple.com/library/ios/samplecode/QuartzDemo/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007531">example code</a>。</p>
<p>​</p>
</li>
</ul>
<p><code>QuartzCore.framework</code></p>
<ul>
<li><p><a target="_blank" rel="noopener" href="https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/Animation_Overview/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004952">Core Animation</a>: objectivec API 做二维动画。.</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_intro/ci_intro.html#//apple_ref/doc/uid/TP30001185">Core Image</a>: 图像和视频处理（滤镜，扭曲，转换）。iOS 5</p>
<p>​</p>
<p><strong>下面列出了Quartz 2D包含的数据类型</strong>：</p>
</li>
<li><p>CGPathRef：用于向量图，可创建路径，并进行填充或描画(stroke)</p>
</li>
<li><p>CGImageRef：用于表示bitmap图像和基于采样数据的bitmap图像遮罩。</p>
</li>
<li><p>CGLayerRef：用于表示可用于重复绘制(如背景)和幕后(offscreen)绘制的绘画层</p>
</li>
<li><p>CGPatternRef：用于重绘图</p>
</li>
<li><p>CGShadingRef、CGGradientRef：用于绘制渐变</p>
</li>
<li><p>CGFunctionRef：用于定义回调函数，该函数包含一个随机的浮点值参数。当为阴影创建渐变时使用该类型</p>
</li>
<li><p>CGColorRef, CGColorSpaceRef：用于告诉Quartz如何解释颜色</p>
</li>
<li><p>CGImageSourceRef,CGImageDestinationRef：用于在Quartz中移入移出数据</p>
</li>
<li><p>CGFontRef：用于绘制文本</p>
</li>
<li><p>CGPDFDictionaryRef, CGPDFObjectRef, CGPDFPageRef, CGPDFStream, CGPDFStringRef, and CGPDFArrayRef：用于访问PDF的元数据</p>
</li>
<li><p>CGPDFScannerRef, CGPDFContentStreamRef：用于解析PDF元数据</p>
</li>
<li><p>CGPSConverterRef：用于将PostScript转化成PDF。在iOS中不能使用。</p>
<p>​</p>
</li>
</ul>
<p><strong>绘图创建步骤（重写drawRect函数）</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">1、我们首先需要开启图形上下文`CGContextRef ctx = UIGraphicsGetCurrentContext();</span><br><span class="line">   //为C语言，创建对象无需加*`。</span><br><span class="line">2、然后对我们想绘制的图片或者图形进行一系列的操作（添加路径，设置属性等）。</span><br><span class="line">3、最后就是渲染在我的View上面。</span><br></pre></td></tr></table></figure>



<h5 id="图像的重绘（刷帧）"><a href="#图像的重绘（刷帧）" class="headerlink" title="图像的重绘（刷帧）"></a>图像的重绘（刷帧）</h5><p>调用重绘view对象的</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (void)setNeedsDisplay; 刷新全部view</span><br><span class="line">- (void)setNeedsDisplayInRect:(CGRect)rect; 刷新区域为rect的view</span><br></pre></td></tr></table></figure>

<h4 id="drawRect方法使用注意点"><a href="#drawRect方法使用注意点" class="headerlink" title="drawRect方法使用注意点"></a>drawRect方法使用注意点</h4><ul>
<li>在iOS开发中不允许开发者直接调用<code>drawRect:</code>方法，刷新绘制内容需要调用<code>setNeedsDisplay</code>方法。</li>
<li>若使用CALayer绘图，只能在drawInContext: 中（类似于drawRect）绘制，或者在delegate中的相应方法绘制。同样也是调用setNeedDisplay等间接调用以上方法</li>
<li>若要实时画图，不能使用gestureRecognizer，只能使用touchbegan等方法来调用setNeedsDisplay实时刷新屏幕</li>
<li>凡是“UI”开头的相关绘图函数，都是UIKit对<code>Core Graphics</code>的封装</li>
</ul>
<h3 id="画图事例"><a href="#画图事例" class="headerlink" title="画图事例"></a>画图事例</h3><p><strong>常用属性</strong></p>
<blockquote>
<p> 设置线段的宽度 				        	 <code>CGContextSetLineWidth</code><br> 设置线段颜色  					   	 <code>CGContextSetRGBStrokeColor</code><br> 设置起点和终点样式（圆角，直角等）       <code>CGContextSetLineCap</code><br> 设置连接点样式（圆角，尖角等） 		 <code>CGContextSetLineJoin</code><br> 设置竖线  							 <code>CGContextSetLineDash</code><br> 填充颜色（实心） 				         <code>CGContextSetRGBFillColor</code> <code>[[UIColor redColor]setFill]</code></p>
<p> <strong>画虚线的参数</strong>：<br> phase：相位，虚线的起始位置＝通常使用 0 即可，从头开始画虚线<br> lengths:长度的数组<br> count ： lengths 数组的个数<br> CGFloat lengths[2] &#x3D; {20.0,10.0};<br> CGContextSetLineDash(context, 0, lengths, 3);</p>
</blockquote>
<p><strong>主要渲染填充模式CGPathDrawingMode</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">kCGPathStroke:画线（空心），只有边框</span><br><span class="line">kCGPathFill:  填充（实心），只有填充（非零缠绕数填充），不绘制边框</span><br><span class="line">kCGPathEOFill:奇偶规则填充（多条路径交叉时，奇数交叉填充，偶交叉不填充）</span><br><span class="line">kCGPathFillStroke：既有边框又有填充</span><br><span class="line">kCGPathEOFillStroke：奇偶填充并绘制边框</span><br></pre></td></tr></table></figure>

<p><strong>官方Demo演示图</strong><br><img src="http://7xr7vj.com1.z0.glb.clouddn.com/2016/04/07/Ftet5exO40m3uAl3Got9CG8FiCVE193.gif"></p>
<p><img src="http://7xr7vj.com1.z0.glb.clouddn.com/2016/04/07/Fs-Y6ZgkBaF0h9SCnlsJ3zwWdZ0E193.gif"></p>
<p><img src="http://7xr7vj.com1.z0.glb.clouddn.com/2016/04/07/FttRA8-Ss-ClMWZANxz-QOBIdTqo193.gif"></p>
<p><strong>渲染方式写法</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1. CGContextDrawPath(context, kCGPathStroke);</span><br><span class="line">2. CGContextStrokePath(ctx);</span><br></pre></td></tr></table></figure>

<p><strong>主要画图Api</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">直线</span><br><span class="line">CGContextAddLineToPoint</span><br><span class="line">椭圆</span><br><span class="line">CGContextAddEllipseInRect</span><br><span class="line">矩形</span><br><span class="line">CGContextAddRect</span><br><span class="line">圆</span><br><span class="line">CGContextAddArc</span><br></pre></td></tr></table></figure>



<p><strong>下面所列举C语言和OC画图方式，OC绘图方式为UIBezierPath</strong></p>
<ul>
<li>方式一:C语言的方式</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">- (void)drawRect:(CGRect)rect</span><br><span class="line"> &#123;</span><br><span class="line">     CGContextRef ctx = UIGraphicsGetCurrentContext();</span><br><span class="line">     CGContextMoveToPoint(ctx,50, 50);</span><br><span class="line">     CGContextAddLineToPoint(ctx, 110, 120);</span><br><span class="line">     CGContextAddLineToPoint(ctx, 150, 40);</span><br><span class="line">     CGContextSetLineWidth(ctx, 10);</span><br><span class="line">     CGContextStrokePath(ctx);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>方式二:C语言的方式之path</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">-</span> (void)drawRect:(<span class="type">CGRect</span>)rect</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取路径</span></span><br><span class="line">    <span class="type">CGMutablePathRef</span> path <span class="operator">=</span> <span class="type">CGPathCreateMutable</span>();</span><br><span class="line">    <span class="type">CGPathMoveToPoint</span>(path, <span class="type">NULL</span>, <span class="number">50</span>, <span class="number">50</span>);</span><br><span class="line">    <span class="type">CGPathAddLineToPoint</span>(path, <span class="type">NULL</span>, <span class="number">110</span>, <span class="number">120</span>);</span><br><span class="line">    <span class="comment">// 将路径添加到上下文中</span></span><br><span class="line">    <span class="type">CGContextAddPath</span>(ctx, path);</span><br><span class="line"></span><br><span class="line"> <span class="type">CGContextStrokePath</span>(ctx)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>方式三:UIBezierPath</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">-</span> (void)drawRect:(<span class="type">CGRect</span>)rect</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line"></span><br><span class="line">    <span class="type">UIBezierPath</span> <span class="operator">*</span>path <span class="operator">=</span> [[<span class="type">UIBezierPath</span> alloc]<span class="keyword">init</span>];</span><br><span class="line">    [path moveToPoint:<span class="type">CGPointMake</span>(<span class="number">50</span>, <span class="number">50</span>)];</span><br><span class="line">    [path addLineToPoint:<span class="type">CGPointMake</span>(<span class="number">110</span>, <span class="number">120</span>)];</span><br><span class="line">    <span class="type">CGContextAddPath</span>(ctx, path.<span class="type">CGPath</span>);</span><br><span class="line"></span><br><span class="line">    <span class="type">CGContextStrokePath</span>(ctx);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li>方式四:C(CGPath) + OC(UIBezierPath)</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">- (void)drawRect:(CGRect)rect</span><br><span class="line">  &#123;</span><br><span class="line">      CGContextRef ctx = UIGraphicsGetCurrentContext();</span><br><span class="line"></span><br><span class="line">      CGMutablePathRef path = CGPathCreateMutable();</span><br><span class="line">      CGPathMoveToPoint(path, NULL, 50, 50);</span><br><span class="line">      CGPathAddLineToPoint(path, NULL, 110, 120);</span><br><span class="line"></span><br><span class="line">      // 把c的路径CGPath转成oc的路径bezierPath</span><br><span class="line">      UIBezierPath *path1 = [UIBezierPath bezierPathWithCGPath:path];</span><br><span class="line">      [path1 addLineToPoint:CGPointMake(80, 80)];</span><br><span class="line"></span><br><span class="line">      // 把路径添加到上下文中</span><br><span class="line">      CGContextAddPath(ctx, path1.CGPath);</span><br><span class="line"></span><br><span class="line">      CGContextStrokePath(ctx);</span><br><span class="line"></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>方式五:纯OC实现(UIBezierPath)</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (void)drawRect:(CGRect)rect</span><br><span class="line"> &#123;</span><br><span class="line">     UIBezierPath *path = [UIBezierPath bezierPath];</span><br><span class="line">     [path moveToPoint:CGPointMake(50, 50)];</span><br><span class="line">     [path addLineToPoint:CGPointMake(110, 120)];</span><br><span class="line">     [path stroke];</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>



<p><strong>直线</strong></p>
<p>两点一线，  <code>x0=x1&amp;&amp;y0！=y1</code> 垂直线   <code>x0！=x1&amp;&amp;y0=y1</code>水平线</p>
<p>起点  <code>CGContextMoveToPoint(ctx,x0,y0);</code></p>
<p>终点 <code>CGContextAddLineToPoint(ctx,x1,y1);</code></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//<span class="doctag">TODO:</span> 画直线</span></span><br><span class="line"><span class="operator">-</span>(void)drawLine</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获得当前画板（图形上下文对象）为C语言，创建对象无需加*</span></span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//!!!: 相关属性设置 可选</span></span><br><span class="line">    <span class="comment">//设置线条的颜色</span></span><br><span class="line">    <span class="comment">//CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0);</span></span><br><span class="line">    <span class="type">CGContextSetStrokeColorWithColor</span>(ctx, [<span class="type">UIColor</span> redColor].<span class="type">CGColor</span>);</span><br><span class="line">    <span class="type">CGContextSetLineWidth</span>(ctx, <span class="number">10</span>); <span class="comment">// 设置线段的宽度</span></span><br><span class="line">    <span class="type">CGContextSetLineJoin</span>(ctx, kCGLineJoinRound); <span class="comment">// 设置线段起点和终点的样式都为圆角</span></span><br><span class="line">    <span class="type">CGContextSetLineCap</span>(ctx, kCGLineCapRound);   <span class="comment">// 设置线段的转角样式为圆角</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//开始画线, x，y为开始点的坐标</span></span><br><span class="line">    <span class="type">CGContextMoveToPoint</span>(ctx, <span class="number">0</span>, <span class="number">40</span>);</span><br><span class="line">    <span class="comment">//画直线, x，y为线条结束点的坐标</span></span><br><span class="line">    <span class="type">CGContextAddLineToPoint</span>(ctx, <span class="keyword">self</span>.bounds.size.width,<span class="number">40</span>);</span><br><span class="line">    <span class="type">CGContextStrokePath</span>(ctx);<span class="comment">//渲染，绘制出一条空心的线段</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p><strong>三角形</strong></p>
<p>三角形是由直线组成，画线方法与直线一样，最少3个点，添加三个点然后闭合路径<code>CGContextClosePath</code></p>
<p><code>CGContextMoveToPoint(triangle, 0, 0)</code>; &#x2F;&#x2F; 设置起点1<br><code>CGContextAddLineToPoint(triangle, 100, 200)</code>; &#x2F;&#x2F; 设置第二个点2<br><code>CGContextAddLineToPoint(triangle,200, 0)</code>; &#x2F;&#x2F; 设置第三个点3</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//<span class="doctag">TODO:</span> 三角形</span></span><br><span class="line"><span class="operator">-</span> (void)drawTriangle</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> triangle <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>(); <span class="comment">// 获得图形上下文</span></span><br><span class="line">    <span class="type">CGContextMoveToPoint</span>(triangle, <span class="number">150</span>, <span class="number">40</span>); <span class="comment">// 设置起点</span></span><br><span class="line">    <span class="type">CGContextAddLineToPoint</span>(triangle, <span class="number">60</span>, <span class="number">200</span>); <span class="comment">// 设置第二个点</span></span><br><span class="line">    <span class="type">CGContextAddLineToPoint</span>(triangle,<span class="number">240</span>, <span class="number">200</span>); <span class="comment">// 设置第三个点</span></span><br><span class="line">    <span class="type">CGContextClosePath</span>(triangle); <span class="comment">// 关闭起点和终点</span></span><br><span class="line">    <span class="type">CGContextStrokePath</span>(triangle); <span class="comment">// 渲染，绘制出三角形</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>矩形</strong></p>
<p>设置一个CGRect大小可以了<code>CGContextAddRect(CGContextRef ctx, CGRect rect)</code></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//<span class="doctag">TODO:</span> 矩形</span></span><br><span class="line"><span class="operator">-</span>(void)drawaRect</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获得当前画板</span></span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line">    <span class="comment">//颜色</span></span><br><span class="line">    <span class="type">CGContextSetRGBStrokeColor</span>(ctx, <span class="number">0.2</span>, <span class="number">0.2</span>, <span class="number">0.2</span>, <span class="number">1.0</span>);</span><br><span class="line">    <span class="comment">//画线的宽度</span></span><br><span class="line">    <span class="type">CGContextSetLineWidth</span>(ctx, <span class="number">0.25</span>);</span><br><span class="line">    <span class="type">CGContextAddRect</span>(ctx, <span class="type">CGRectMake</span>(<span class="number">2</span>, <span class="number">2</span>, <span class="number">30</span>, <span class="number">30</span>));</span><br><span class="line">    <span class="type">CGContextStrokePath</span>(ctx);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>圆<code>CGContextAddArc</code></strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  画圆</span></span><br><span class="line"><span class="comment"> *  @param ctx        上下文</span></span><br><span class="line"><span class="comment"> *  @param x          圆起点坐标X</span></span><br><span class="line"><span class="comment"> *  @param y          圆起点坐标y</span></span><br><span class="line"><span class="comment"> *  @param radius     圆的半径</span></span><br><span class="line"><span class="comment"> *  @param startAngle 起始角度</span></span><br><span class="line"><span class="comment"> *  @param endAngle   结束角度</span></span><br><span class="line"><span class="comment"> *  @param clockwise  顺逆时针</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">CGContextAddArc</span>(<span class="type">CGContextRef</span> ctx, <span class="type">CGFloat</span> x, <span class="type">CGFloat</span> y,<span class="type">CGFloat</span> radius, <span class="type">CGFloat</span> startAngle, <span class="type">CGFloat</span> endAngle, int clockwise)</span><br></pre></td></tr></table></figure>



<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//<span class="doctag">TODO:</span> 画圆</span></span><br><span class="line"><span class="operator">-</span> (void)drawRoundRect</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line">    <span class="type">CGContextSetRGBStrokeColor</span>(ctx, <span class="number">0.2</span>, <span class="number">0.2</span>, <span class="number">0.2</span>, <span class="number">1.0</span>);<span class="comment">//颜色</span></span><br><span class="line">    <span class="type">CGContextSetLineWidth</span>(ctx, <span class="number">0.25</span>);<span class="comment">//画线的宽度</span></span><br><span class="line"></span><br><span class="line">    <span class="type">CGPoint</span> center <span class="operator">=</span> <span class="type">CGPointMake</span>(<span class="keyword">self</span>.bounds.size.width <span class="operator">/</span> <span class="number">2</span>, <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>);<span class="comment">//设置圆心位置</span></span><br><span class="line">    <span class="type">CGFloat</span> radius <span class="operator">=</span> <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>;<span class="comment">//设置半径</span></span><br><span class="line">    <span class="type">CGFloat</span> startAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span>;<span class="comment">//圆起点位置</span></span><br><span class="line">    <span class="type">CGFloat</span> endAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span> <span class="operator">+</span>  <span class="type">M_PI</span> <span class="operator">*</span> <span class="number">2</span>;<span class="comment">//圆终点位置</span></span><br><span class="line">    <span class="type">CGContextAddArc</span>(ctx,center.x,center.y,radius,startAngle, endAngle, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="type">CGContextDrawPath</span>(ctx, kCGPathStroke); <span class="comment">//绘制路径</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="环形"><a href="#环形" class="headerlink" title="环形"></a>环形</h3><p>环形其实就是有一定宽度边框圆，所以我们设置一定的线宽即可如：<code>CGContextSetLineWidth(ctx, 10);</code></p>
<p>环形是空心圆，所以<code>CGContextDrawPath(ctx, kCGPathStroke);</code></p>
<p>绘制方式选择kCGPathStroke只画线，不填充，填充那就是个实心圆了</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//<span class="doctag">TODO:</span> 环形</span></span><br><span class="line"><span class="operator">-</span>(void)drawAnnular</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line"></span><br><span class="line">    <span class="type">CGPoint</span> center <span class="operator">=</span> <span class="type">CGPointMake</span>(<span class="keyword">self</span>.bounds.size.width <span class="operator">/</span> <span class="number">2</span>, <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>);<span class="comment">//设置圆心位置</span></span><br><span class="line">    <span class="type">CGFloat</span> radius <span class="operator">=</span> <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>;<span class="comment">//设置半径</span></span><br><span class="line">    <span class="type">CGFloat</span> startAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span>;<span class="comment">//圆起点位置</span></span><br><span class="line">    <span class="type">CGFloat</span> endAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span> <span class="operator">+</span>  <span class="type">M_PI</span> <span class="operator">*</span> <span class="number">2</span>;<span class="comment">//圆终点位置</span></span><br><span class="line">    <span class="type">CGContextAddArc</span>(ctx,center.x,center.y,radius<span class="operator">-</span><span class="number">5</span>,startAngle, endAngle, <span class="number">0</span>);</span><br><span class="line">    <span class="type">CGContextSetLineWidth</span>(ctx, <span class="number">10</span>);</span><br><span class="line">    [[<span class="type">UIColor</span> greenColor]<span class="keyword">set</span>];</span><br><span class="line">    <span class="type">CGContextDrawPath</span>(ctx, kCGPathStroke); <span class="comment">//绘制路径</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>圆弧</strong></p>
<p>绘制圆弧 就是一个圆形的一部分</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">-</span>(void)circularArc</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> context <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line">    <span class="type">CGPoint</span> center <span class="operator">=</span> <span class="type">CGPointMake</span>(<span class="keyword">self</span>.bounds.size.width <span class="operator">/</span> <span class="number">2</span>, <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>);<span class="comment">//设置圆心位置</span></span><br><span class="line">    <span class="type">CGFloat</span> radius <span class="operator">=</span> <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>;<span class="comment">//设置半径</span></span><br><span class="line">    <span class="type">CGFloat</span> startAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span>;<span class="comment">//圆起点位置</span></span><br><span class="line">    <span class="type">CGFloat</span> endAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span> <span class="operator">+</span>  <span class="type">M_PI</span><span class="operator">*</span><span class="number">1.2</span>;<span class="comment">//圆终点位置</span></span><br><span class="line">    <span class="type">CGContextAddArc</span>(context, center.x,center.y,radius,startAngle, endAngle, <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//绘制圆弧</span></span><br><span class="line">    <span class="type">CGContextDrawPath</span>(context, kCGPathStroke);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>椭圆</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (void)drawRect:(CGRect)rect</span><br><span class="line">&#123;</span><br><span class="line">    CGContextRef circular = UIGraphicsGetCurrentContext();</span><br><span class="line">    CGContextAddEllipseInRect(circular, CGRectMake(100, 100, 100, 80));//宽高相等=圆，宽高不等=椭圆</span><br><span class="line">    CGContextSetRGBFillColor(circular, 1.0, 0, 1.0, 1);// 设置颜色</span><br><span class="line">    CGContextFillPath(circular); // 渲染，将实心圆形画出</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>扇形</strong></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">-</span>(void)drawPie</span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">CGContextRef</span> ctx <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line"></span><br><span class="line">    <span class="type">CGPoint</span> center <span class="operator">=</span> <span class="type">CGPointMake</span>(<span class="keyword">self</span>.bounds.size.width <span class="operator">/</span> <span class="number">2</span>, <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>);<span class="comment">//设置圆心位置</span></span><br><span class="line">    <span class="type">CGFloat</span> radius <span class="operator">=</span> <span class="keyword">self</span>.bounds.size.height <span class="operator">/</span> <span class="number">2</span>;<span class="comment">//设置半径</span></span><br><span class="line"></span><br><span class="line">    <span class="type">CGFloat</span> startAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span>;<span class="comment">//圆起点位置</span></span><br><span class="line">    <span class="type">CGFloat</span> endAngle <span class="operator">=</span> <span class="operator">-</span> <span class="type">M_PI_2</span> <span class="operator">+</span>  <span class="type">M_PI</span> <span class="operator">*</span> <span class="number">1.5</span>;<span class="comment">//圆终点位置</span></span><br><span class="line">    [[<span class="type">UIColor</span> greenColor]<span class="keyword">set</span>];</span><br><span class="line"></span><br><span class="line">    <span class="comment">//顺时针画扇形</span></span><br><span class="line">    <span class="type">CGContextMoveToPoint</span>(ctx, center.x, center.y);</span><br><span class="line">    <span class="type">CGContextAddArc</span>(ctx, center.x, center.y, radius, startAngle,endAngle, <span class="number">0</span>);</span><br><span class="line">    <span class="type">CGContextClosePath</span>(ctx);</span><br><span class="line">    <span class="type">CGContextDrawPath</span>(ctx, kCGPathEOFillStroke);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="绘制文本内容"><a href="#绘制文本内容" class="headerlink" title="绘制文本内容"></a>绘制文本内容</h4><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//绘图只能在当前位方法中调用,否则无法得到图形上下文</span></span><br><span class="line"><span class="operator">-</span> (void)drawRect:(<span class="type">CGRect</span>)rect&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//要显示的文字</span></span><br><span class="line">    <span class="type">NSString</span> <span class="operator">*</span>str <span class="operator">=</span> @<span class="string">&quot;这是要现实的文本Text。。。。&quot;</span>;</span><br><span class="line">    <span class="comment">//绘制文字显示的指定区域</span></span><br><span class="line">    <span class="type">CGRect</span> rect <span class="operator">=</span> <span class="type">CGRectMake</span>(<span class="number">20</span>, <span class="number">50</span>, <span class="number">374</span>, <span class="number">500</span>);</span><br><span class="line">    <span class="comment">//字体大小</span></span><br><span class="line">    <span class="type">UIFont</span> <span class="operator">*</span>font <span class="operator">=</span> [<span class="type">UIFont</span> systemFontOfSize:<span class="number">25</span>];</span><br><span class="line">    <span class="comment">//字体颜色</span></span><br><span class="line">    <span class="type">UIColor</span> <span class="operator">*</span>color <span class="operator">=</span> [<span class="type">UIColor</span> redColor];</span><br><span class="line">    <span class="comment">//初始化段落样式</span></span><br><span class="line">    <span class="type">NSMutableParagraphStyle</span> <span class="operator">*</span>paragraphStyle <span class="operator">=</span> [[<span class="type">NSMutableParagraphStyle</span> alloc]<span class="keyword">init</span>];</span><br><span class="line">    <span class="comment">//居中对齐</span></span><br><span class="line">    <span class="type">NSTextAlignment</span> textAlignment <span class="operator">=</span> <span class="type">NSTextAlignmentCenter</span>;</span><br><span class="line">    <span class="comment">//设置段落样式</span></span><br><span class="line">    paragraphStyle.alignment <span class="operator">=</span> textAlignment;</span><br><span class="line">    <span class="type">NSDictionary</span> <span class="operator">*</span>attributes<span class="operator">=</span> @&#123;<span class="type">NSFontAttributeName</span>:font,<span class="type">NSForegroundColorAttributeName</span>:color,</span><br><span class="line"><span class="type">NSParagraphStyleAttributeName</span>:style&#125;;</span><br><span class="line">    [str drawInRect:rect withAttributes:attributes];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>绘制图片&amp;&amp;图片剪切<code>CGContextClip</code></p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">-</span> (void)drawImage&#123;</span><br><span class="line">     <span class="type">UIImage</span> <span class="operator">*</span>image <span class="operator">=</span> [<span class="type">UIImage</span> imageNamed:@<span class="string">&quot;theImage.jpg&quot;</span>];</span><br><span class="line">    <span class="comment">//从某一点开始绘制</span></span><br><span class="line">    [image drawAtPoint:<span class="type">CGPointMake</span>(<span class="number">10</span>, <span class="number">50</span>)];</span><br><span class="line">    <span class="comment">//绘制到指定的矩形中，注意如果大小不合适会会进行拉伸，图像会形变</span></span><br><span class="line">    [image drawInRect:<span class="type">CGRectMake</span>(<span class="number">10</span>, <span class="number">50</span>, <span class="number">300</span>, <span class="number">450</span>)];</span><br><span class="line">    <span class="comment">//平铺绘制</span></span><br><span class="line"><span class="comment">//    [image drawAsPatternInRect:CGRectMake(0, 0, 320, 568)];</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//绘图只能在当前位方法中调用,否则无法得到图形上下文</span></span><br><span class="line"><span class="operator">-</span> (void)drawRect:(<span class="type">CGRect</span>)rect&#123;</span><br><span class="line">    <span class="comment">//获取图形上下文</span></span><br><span class="line">    <span class="type">CGContextRef</span> context <span class="operator">=</span> <span class="type">UIGraphicsGetCurrentContext</span>();</span><br><span class="line">    <span class="comment">//指定上下文显示的范围</span></span><br><span class="line">    <span class="type">CGContextAddEllipseInRect</span>(context, <span class="type">CGRectMake</span>(<span class="number">80</span>, <span class="number">50</span>, <span class="number">100</span>, <span class="number">100</span>));</span><br><span class="line">    <span class="comment">//裁剪</span></span><br><span class="line">    <span class="type">CGContextClip</span>(context);</span><br><span class="line">    <span class="comment">//获取图片</span></span><br><span class="line">    <span class="type">UIImage</span> <span class="operator">*</span>image <span class="operator">=</span> [<span class="type">UIImage</span> imageNamed:@<span class="string">&quot;mv2.jpg&quot;</span>];</span><br><span class="line">    [image drawAtPoint:<span class="type">CGPointMake</span>(<span class="number">50</span>, <span class="number">50</span>)];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p><strong>截屏</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">//截屏</span><br><span class="line">-(void)cutScreen&#123;</span><br><span class="line">    /*</span><br><span class="line">     1、获得一个图片的画布</span><br><span class="line">    2、获得画布的上下文</span><br><span class="line">    3、设置截图的参数</span><br><span class="line">    4、截图</span><br><span class="line">    5、关闭图片的上下文</span><br><span class="line">    6、保存</span><br><span class="line">    */</span><br><span class="line">   //1、获得一个图片的画布</span><br><span class="line">   UIGraphicsBeginImageContext(self.frame.size);</span><br><span class="line">   //2、获得一个上下文</span><br><span class="line">   [self addRound];</span><br><span class="line">   //3、设置参数</span><br><span class="line">   /*</span><br><span class="line">    CGSize size:截图尺寸</span><br><span class="line">    BOOL opaque：是否不透明,YES不透明</span><br><span class="line">    CGFloat scale：比例</span><br><span class="line">    */</span><br><span class="line">   UIGraphicsBeginImageContextWithOptions(self.frame.size, YES, 1);</span><br><span class="line">   //4、开始截图</span><br><span class="line">   UIImage image = UIGraphicsGetImageFromCurrentImageContext();</span><br><span class="line">   //5、关闭图片上下文</span><br><span class="line">   UIGraphicsEndImageContext();</span><br><span class="line">   //保存到相册</span><br><span class="line">   UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:),nil);</span><br><span class="line">&#125;；</span><br></pre></td></tr></table></figure>



<p><strong>保存到相册时的回调方法</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (void)image:(UIImage )image didFinishSavingWithError:(NSError )error</span><br><span class="line">   contextInfo:(void )contextInfo&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>参考资料推荐</code></p>
<p><a target="_blank" rel="noopener" href="https://www.gitbook.com/book/wf851128/quartz-2d-shou-ce/details"><strong>Quartz 2D手册</strong></a></p>
<p><a target="_blank" rel="noopener" href="http://www.kancloud.cn/manual/ios"><strong>ios核心动画高级技巧</strong></a></p>
<p><a target="_blank" rel="noopener" href="https://github.com/raineryue?tab=repositories">https://github.com/raineryue?tab=repositories</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2016/04/06/iOS绘图与动画系列 Core Graphics与Quartz 2D（一）/">http://huluo666.gitee.io/2016/04/06/iOS绘图与动画系列 Core Graphics与Quartz 2D（一）/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/iOS-%E5%8A%A8%E7%94%BB-%E7%BB%98%E5%9B%BE/">iOS,动画,绘图</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2016/04/07/iOS%20ViewController%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/"><i class="fa fa-chevron-left">  </i><span>iOS ViewController生命周期</span></a></div><div class="next-post pull-right"><a href="/2016/04/06/%E9%A2%9C%E8%89%B2%E6%B8%90%E5%8F%98%20CAGradientLayer/"><span>颜色渐变 CAGradientLayer</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>